package aliyun

import (
	"app/commonutils"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

const BucketName  = "bucket1"
func getBucket() (*oss.Bucket, error) {
	endpoint := "oss-cn-hangzhou.aliyuncs.com"
	bucketName := "ssyerv2"
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		fmt.Println("OSS Error:", err)
		return nil, err
	}

	bucket, err := client.Bucket(bucketName)
	return bucket, err
}

func OssUpload(filename string, filepath string) (objName string, err error) {
	bucket, err := getBucket()
	if err != nil {
		fmt.Printf("Get OSS Bucket ERROR : %v \n", err)
		return "", fmt.Errorf("Get OSS Bucket ERROR : %v \n", err)
	}
	err = bucket.PutObjectFromFile(BucketName+filename, filepath)
	if err != nil {
		fmt.Printf("OSS Upload Error: %v \n", err)
		return "", fmt.Errorf("OSS Upload Error: %v \n", err)
	}
	return BucketName + filename, nil
}

func GetOssImgUrl(objName string) string {
	if strings.HasPrefix(objName,"/") {
		return "https://img.ssyer.com"+objName
	}
	return "https://img.ssyer.com/"+objName
}

type T1 struct {
	Value      string  `json:"value"`
	Confidence float32 `json:"confidence"`
}

type T2 struct {
	Tags []T1 `json:"tags"`
}

func GetImageTags(img_url string) (string, error) {
	host := "dtplus-cn-shanghai.data.aliyuncs.com"
	path := "/image/tag"
	body := struct {
		Type     int    `json:"type"`
		ImageUrl string `json:"image_url"`
	}{0, img_url}
	jsonBody, err := commonutils.Struct2Json(body)
	if err != nil {
		return "", err
	}
	md5Body := commonutils.GetMD5(jsonBody)
	timeStr := time.Now().UTC().String()
	stringToSign := "POST\n" +
		"application/json\n" +
		md5Body + "\n" +
		"application/json\n" +
		timeStr + "\n" +
		path

	signature := commonutils.GetShe1ByKey(stringToSign, accessKeySecret)
	req, err := http.NewRequest(http.MethodPost, "https://"+host+path, strings.NewReader(jsonBody))
	req.Header.Add("accept", "application/json")
	req.Header.Add("content-type", "application/json")
	req.Header.Add("Authorization", "Dataplus "+accessKeyId+":"+signature)
	req.Header.Add("date", timeStr)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	bodyByte, err := ioutil.ReadAll(resp.Body)
	var obj = new(T2)
	_, err = commonutils.Json2Struct(string(bodyByte), obj)
	if err != nil {
		return "", err
	}
	tags := ""
	for _, v := range obj.Tags {
		tags += v.Value + ","
	}
	return tags[:len(tags)-1], nil
}

type FileInfo1 struct {
	FileSize struct{
		Value string `json:"value"`
	} `json:"FileSize"`
	ImageWidth struct{
		Value string `json:"value"`
	} `json:"ImageWidth"`
	ImageHeight struct{
		Value string `json:"value"`
	} `json:"ImageHeight"`
}

type FileInfo2 struct {
	RGB string `json:"RGB"`
}

type FileInfo struct {
	FileInfo1
	FileInfo2
}
func GetOssFileInfo(ObjName string) (info FileInfo, err error) {
	url := GetOssImgUrl(ObjName)
	resp1, err := http.Get(fmt.Sprintf("%s?x-oss-process=image/info",url))
	if err != nil {
		return FileInfo{}, err
	}
	defer resp1.Body.Close()
	bodyByte1, err := ioutil.ReadAll(resp1.Body)
	if err != nil {
		return FileInfo{}, err
	}

	resp2, err := http.Get(fmt.Sprintf("%s?x-oss-process=image/average-hue",url))
	if err != nil {
		return FileInfo{}, err
	}
	defer resp2.Body.Close()
	bodyByte2, err := ioutil.ReadAll(resp2.Body)
	if err != nil {
		return FileInfo{}, err
	}

	var fileInfo1 *FileInfo1 = new(FileInfo1)
	var fileInfo2 *FileInfo2 = new(FileInfo2)
	_, err = commonutils.Json2Struct(string(bodyByte1),fileInfo1)
	_, err = commonutils.Json2Struct(string(bodyByte2),fileInfo2)
	info = FileInfo{
		*fileInfo1,
		*fileInfo2,
	}
	return info,err
}